<template>
  <view class="page-container">
    <!-- 顶部 -->
    <GlobalTopBar ref="topBarRef" class="topbar" :isLeft="true" color="#fff">
    </GlobalTopBar>
    <!-- 内容 -->
    <image
      class="tops"
      :src="`${store.imgDomain}login_top4.jpg`"
      mode="widthFix"
    />

    <view class="page_content">
      <view class="boxs">
        <view class="titles">欢迎登录/注册</view>
        <!-- 手机号 -->
        <view class="phone">
          <input
            v-model="phone"
            class="uni-input"
            type="number"
            focus
            maxlength="11"
            placeholder="请输入手机号"
          />
        </view>
        <!-- 验证码 -->
        <view class="phone yzm">
          <input
            v-model="sms_code"
            class="uni-input"
            type="number"
            placeholder="请输入验证码"
            maxlength="10"
          />
          <view
            class="yzmtext"
            :class="{ ac: yzmText != '获取验证码' }"
            @click="sendSmsCode"
            >{{ yzmText }}</view
          >
        </view>
        <button class="btn" @click="loginFun">登录 / 注册</button>
        <label class="radio" @click="radiovalue = !radiovalue"
          ><radio
            style="transform: scale(0.8)"
            color="#16CCBB"
            value="1"
            :checked="radiovalue"
          /><text
            >我已阅读并同意
            <text
              style="color: #16ccbb"
              @click.stop="
                store.to(
                  '/pages/public/agreement?url=wxapp/login/getUserAgreement',
                )
              "
              >《用户协议》</text
            >和
            <text
              style="color: #16ccbb"
              @click.stop="
                store.to(
                  '/pages/public/agreement?url=wxapp/login/getPrivacyPolicy',
                )
              "
              >《隐私条款》</text
            ></text
          ></label
        >
      </view>

      <y-drawer
        ref="drawerRef"
        :borderRadius="20"
        :maskClosable="true"
        :length="700"
      >
        <nameimg @hadeorname="gethadeornameFun" />
      </y-drawer>
    </view>
  </view>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useCounterStore } from '@/store';
import request from '@/utils/request';
import { validatePhone } from '@/utils/validate';
import nameimg from '../../components/nameimg.vue';

const title = ref('hello');
const radiovalue = ref(false);
const nickorhide = ref(false);
const drawerRef = ref(null);
const store = useCounterStore();
const phone = ref('');
const sms_code = ref('');
const yzmText = ref('获取验证码');

// 获取新用户头像昵称
const gethadeornameFun = (data) => {
  store.nick_name = data.nickname;
  store.headimg = data.headimg;
  doRegister();
};

// 发送短信验证码接口（小程序手动登录
const sendSmsCode = async () => {
  if (yzmText.value !== '获取验证码') return;
  if (!radiovalue.value) {
    uni.showToast({
      title: '请先阅读并同意《用户协议》和《隐私条款》',
      icon: 'none',
    });
    return;
  }
  if (validatePhone(phone.value)) {
    const data = await request('wxapp/login/sendSmsCode', {
      mobile: phone.value,
    });
    let num = 60;
    yzmText.value = 60;
    const timer = setInterval(() => {
      num--;
      yzmText.value = num;
      if (num === 0) {
        clearInterval(timer);
        yzmText.value = '获取验证码';
      }
    }, 1000);
  } else {
    uni.showToast({
      title: `请填写正确的手机号`,
      icon: 'none',
    });
  }
};

// 登录
const loginFun = async () => {
  if (!phone.value) {
    uni.showToast({
      title: `请填写正确的手机号`,
      icon: 'none',
    });
    return;
  }
  if (!sms_code.value) {
    uni.showToast({
      title: `请填写验证码`,
      icon: 'none',
    });
    return;
  }
  clearInterval(store.times);
  store.times = setInterval(() => {
    uni.getSetting({
      withSubscriptions: true,
      success(res) {
        console.log('查询了', res);

        store.subscriptionsSetting = res.subscriptionsSetting;
      },
    });
  }, 1000);
  if (
    ['reject', 'ban'].includes(
      store.subscriptionsSetting['WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'],
    )
  ) {
    uni.showToast({
      title: '请先点击右上角三个点设置订阅消息为允许在登录',
      icon: 'none',
    });
  } else if (
    store.subscriptionsSetting['WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'] ==
    'accept'
  ) {
    uni.login({
      provider: 'weixin', //使用微信登录
      success: async function (res) {
        if (store.open_id) {
          doLogin();
          return;
        }
        await getOpenId(res.code);
      },
    });
  } else {
    uni.requestSubscribeMessage({
      tmplIds: [
        'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw',
        'bLdc3rHrTBhaRtDRhYcw5XI6oDOAppWo8C27UPpLT-g',
      ], // 替换为实际模板ID，
      async success(res) {
        if (res.WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw === 'accept') {
          store.subscriptionsSetting[
            'WrCPvJR0hWlnuUJtepFtYQZ1dNGeESwtDdserfNkJsw'
          ] = 'accept';

          await uni.login({
            provider: 'weixin', //使用微信登录
            success: async function (res) {
              if (store.open_id) {
                doLogin();
                return;
              }
              await getOpenId(res.code);
            },
          });
        } else {
          uni.showToast({
            title: '请先订阅消息才可登录',
            icon: 'none',
          });
        }
      },
      fail() {
        console.log('失败');
      },
      complete() {},
    });
  }
};

// 通过code获取微信用户Openid
const getOpenId = async (code) => {
  const data = await request('wxapp/login/getOpenId', { code });
  store.open_id = data.openid;
  uni.setStorageSync('open_id', store.open_id);
  doLogin();
};

// 登录
const doLogin = async () => {
  const datas = {
    login_type: 2,
    phone: phone.value,
    sms_code: sms_code.value,
  };
  request('worker/login/doLogin', datas)
    .then((res) => {
      store.workerData = res;
      store.phone = phone.value;
      uni.setStorageSync('phone', phone.value);
      if (res.status === 2) {
        store.is_type = 2;
        uni.setStorageSync('is_type', 2);
        uni.redirectTo({
          url: '/pages/master/home/index',
        });
      } else {
        store.to('/pages/masterlogin/master');
      }
    })
    .catch((err) => {
      if (err.data.msg === '当前账号不存在,请注册') {
        // store.phone = phone.value;
        // uni.setStorageSync('phone', phone.value);
        // store.to('/pages/masterlogin/master');
        uni.showToast({
          title: '暂无师傅信息',
          icon: 'none',
        });
      } else if (err.data.msg === '账号已被禁用') {
        uni.showToast({
          title: '您的账号已被禁用，请联系客服处理',
          icon: 'none',
        });
      } else if (err.data.msg === '验证码错误') {
        uni.showToast({
          title: '验证码错误',
          icon: 'none',
        });
      }
    });
};
// 个人会员注册
const doRegister = async () => {
  const datas = {
    register_type: 2,
    phone: phone.value,
    nick_name: store.nick_name,
    headimg: store.headimg,
    sms_code: sms_code.value,
  };
  const data = await request('wxapp/login/doRegister', datas);
  uni.redirectTo({
    url: '/pages/home/index',
  });
  store.userInfo = data;
  console.log('注册成功', data);
};
</script>
<style scoped lang="scss">
.topbar {
  position: relative;
  z-index: 10;
}
.page-container {
  position: relative;
  justify-content: center;
  background-color: #ffffff;
  .page_image {
    width: 750rpx;
    height: 502rpx;
  }
}
.page_content {
  position: relative;
  z-index: 9;
  padding: 430rpx 63rpx 0;
  box-sizing: border-box;
}
.btn {
  height: 90rpx;
  line-height: 90rpx;
  color: #fff;
  background-color: #13c5b4;
  border-radius: 45rpx;
  font-size: 30rpx;
  text-align: center;
}
.radio {
  margin-top: 30rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  text {
    color: $uni-text-color-grey;
    font-size: 24rpx;
  }
}

.qttext {
  position: relative;
  width: max-content;
  margin: 160rpx auto 25rpx;
  color: $uni-text-color-grey;
  font-size: 24rpx;
  padding: 0 15rpx;
  &::after {
    content: ' ';
    position: absolute;
    top: 50%;
    left: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #0086f2;
  }
  &::before {
    content: ' ';
    position: absolute;
    top: 50%;
    right: -40rpx;
    transform: translateY(-50%);
    width: 40rpx;
    height: 1rpx;
    background-color: #0086f2;
  }
}
.login_iphone {
  display: block;
  margin: 0 auto;
  width: 89rpx;
  height: 89rpx;
}
.logo {
  display: block;
  width: 282rpx;
  height: 108rpx;
  display: block;
  margin: 100rpx auto 20rpx;
}
.hytext {
  text-align: center;
  font-size: 36rpx;
  margin-bottom: 100rpx;
}
.tlef {
  width: 40rpx;
  display: flex;
  justify-content: center;
}
.phone {
  box-sizing: border-box;
  padding: 0 20rpx;
  display: flex;
  align-items: center;
  margin: 20rpx 0;
  background-color: #e0fdfa;
  border-radius: 10rpx;
  .phoneimg {
    width: 30rpx;
    height: 42rpx;
  }
  .uni-input {
    flex: 1;
    height: 90rpx;
    box-sizing: border-box;
    padding-left: 20rpx;
  }
}
.yzm {
  .phoneimg {
    width: 38rpx;
    height: 44rpx;
  }
  .yzmtext {
    flex-shrink: 0;
    position: relative;
    width: 30%;
    text-align: center;
    line-height: 90rpx;
    font-size: 30rpx;
    color: #15c9b8;
    &.ac {
      color: $uni-text-color-grey;
    }
    &::after {
      content: ' ';
      position: absolute;
      top: 50%;
      left: -20rpx;
      width: 1rpx;
      height: 44rpx;
      transform: translateY(-50%);
      background-color: #16ccbb;
    }
  }
}

.tops {
  position: absolute;
  top: 0;
  left: 0;
  width: 750rpx;
  height: 698rpx;
}
.boxs {
  background-color: #fff;
  border: 1rpx solid #83f1e6;
  border-radius: 20rpx;

  box-sizing: border-box;
  padding: 40rpx;

  margin: 0 auto;
  .titles {
    text-align: center;
    font-size: 36rpx;
  }
}
</style>
